import { login } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'
export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    siderType: true,
    lang: localStorage.getItem('lang') || 'zh',
    staff: JSON.parse(localStorage.getItem('staff')) || {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    changeSiderType(state) {
      state.siderType = !state.siderType
    },
    changLang(state, lang) {
      state.lang = lang
    },
    SAVESTAFF(state, staff) {
      state.staff.staff_number = staff.staff_number
      state.staff.staff_name = staff.staff_name
      localStorage.setItem('staff', JSON.stringify(state.staff))
    }
  },
  actions: {
    async login({ commit }, userInfo) {
      const result = await login(userInfo)
      if (result.code === 200) {
        const token = '123456789'
        commit('SAVESTAFF', result.data)
        commit('setToken', token)
        setTokenTime()
        router.replace('/')
        return 'OK'
      } else {
        return Promise.resolve(new Error('出错了！'))
      }
      // return new Promise((resolve, reject) => {
      //   loginApi(userInfo)
      //     .then((res) => {
      //       console.log(res)
      //       commit('setToken', res.token)
      //       setTokenTime()
      //       router.replace('/')
      //       resolve()
      //     })
      //     .catch((err) => {
      //       reject(err)
      //     })
      // })
    },
    // 退出
    logout({ commit }) {
      commit('setToken', '')
      localStorage.clear()
      router.replace('/login')
    }
  }
}
